# 读取数据
import pandas as pd
import matplotlib.pyplot as  plt
import warnings
import seaborn as sns
warnings.filterwarnings('ignore')
df=pd.read_csv('train.csv')
print(df.head())
# 将datetime列，切分出年月日时
df['月']=df['datetime'].apply(lambda x:int(x.split()[0].split('-')[1]))
df['日']=df['datetime'].apply(lambda x:int(x.split()[0].split('-')[2]))
df['时']=df['datetime'].apply(lambda x:int(x.split()[1].split(':')[0]))
# 按照小时，统计用车数量
#bar:条形图
#line：折线图
#kde：密度图
# df.groupby('时')['count'].sum().plot(kind='line')
# plt.show()
# 最终按照上班高峰，下班高峰，白天低谷，晚上低谷，分成四个小时段
def a(x):
    if x>=0 and x<=6:
        return 0
    elif x>=7 and x<=10:
        return 1
    elif x>11 and x<=15:
        return 2
    else:
        return 3
df['时段']=df['时'].map(a)
# # 将cnt中的噪音值用箱线图进行显示
# sns.boxplot(y='count',data=df)
# plt.show()
# 显示非噪音数据的比例
miu=df['count'].mean()
sigma=df['count'].std()
noise=df[abs(df['count']-miu)>(3*sigma)]
nonoise=df[abs(df['count']-miu)<(3*sigma)]
bili=len(nonoise)/(len(noise)+len(nonoise))
print(bili)
# 删除噪音数据（保留非噪音数据）
df=nonoise
# 绘制所有连续特征的热图   将连续值中关系大于0.6的数据删除一项
# temp,atemp,humidity,windspeed,casual,registered,count
cor=df[['temp','atemp','humidity','windspeed','casual','registered','count']].corr()
sns.heatmap(cor,annot=True)
plt.show()
del df['atemp']
del df['casual']
del df['registered']
# 绘制假日和非假日不同小时用车辆
df1=df.groupby(['workingday','时'])['count'].sum().reset_index()
sns.pointplot(x='时',y='count',hue='workingday',data=df1)
plt.show()
# 绘制不同季节不同小时的用车辆
df2=df.groupby(['season','时'])['count'].sum().reset_index()
sns.pointplot(x='时',y='count',hue='season',data=df2)
plt.show()
#设定temp','humidity','windspeed' 为特征
x=df[['temp','humidity','windspeed']]
#设定count为标签
y=df['count']
# 将数据切分为训练集和测试集
from sklearn.model_selection import train_test_split
train_x,test_x,train_y,test_y=train_test_split(x,y,train_size=0.7)
# 分别使用L1正则和L2正则处理模型
from sklearn.linear_model import Lasso,Ridge
from sklearn.model_selection import GridSearchCV
l1=Lasso()
l2=Ridge()
a={'alpha':[0.1,0.2,0.3,0.4,0.5,0.7,0.9,1.1]}
# 找到最优模型和最优得分
gri1=GridSearchCV(estimator=l1,param_grid=a,cv=6)
gri2=GridSearchCV(l2,a,cv=6)

gri1.fit(train_x,train_y)
gri2.fit(train_x,train_y)

print(gri1.best_score_)
print(gri1.best_params_)
print(gri2.best_score_)
print(gri2.best_params_)